// pages/new-pages/home/home.js
const app = getApp();
import Toast from '../../../component/toast/toast';
import IMController from '../../../controller/im.js';
let cerealsToast = null;
Page({

    /**
     * 页面的初始数据
     */
    data: {
        pageSize: 10,
        pageIndex: -1,
        hasMore: true,
        resumeList: [],
        popupObj: {
            isShowPopup: false,
            isAnim: false
        },
        filterParams: null,
        positionFilter:null,
        popupTop: '240px',
        currentCity:'',
        indicatordots:true,
        autoplay:true,
        interval:10000,
        duration:1000
    },
    getBannersData() {
        let that = this;
        wx.request({
            url: app.globalData.serverAddress.getBanners,
            success: function(res) {
                console.log("getBannersData", res);
                if (res.statusCode == 200) {
                    if (res.data.CodeStatus == 20000) {
                        let imgArr = [];
                        res.data.BodyContent.forEach(function(arr) {
                            imgArr.push(arr.ImgUrl);
                        });
                        that.setData({
                            bannerImgs: imgArr
                        });
                    }
                }
            },
            fail: function(res) {
                console.log(JSON.stringify(res));
            },
            complete: function(res) {}
        });
    },
    //获取简历列表
    getQueryResumes(_data, isReach) {
        let that = this;
        let pageI = ++that.data.pageIndex;
        if (!isReach) {
            pageI = 0;
            that.setData({
                hasMore: true
            });
            wx.showLoading({
                title: '加载中...',
                mask: true
            });
        }
        if (!that.data.hasMore) return;
        let data = {};
        if (_data) {
            data = _data;
            data.pageIndex = pageI;
        } else {
            data = this.getDefaultFilterData(pageI);
        }
        that.setData({
            pageIndex: pageI
        });
        console.log(data);
        wx.request({
            url: app.globalData.serverAddress.getQueryResumes,
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            data: data,
            method: 'GET',
            success: function(res) {
                console.log("getQueryResumes response", res);
                if (res.statusCode == 200) {
                    if (res.data.CodeStatus == 20000) {
                        let resumeList = res.data.BodyContent.List;
                        let count = res.data.BodyContent.TotalCount;
                        let flag = (that.data.pageIndex + 1) * that.data.pageSize < count;
                        resumeList.forEach(function (arr, index) {
                            let city = resumeList[index].City;
                            if(city){
                              resumeList[index].City = city.substr(0, city.length - 1);
                            }
                        });
                        if (isReach) {
                            resumeList = that.data.resumeList.concat(resumeList);
                        }
                        that.setData({
                            resumeList: resumeList,
                            hasMore: flag
                        })
                    } else {
                        that.setData({
                            resumeList: [],
                            hasMore: false
                        });
                        Toast(res.data.Message);
                    }
                }
            },
            fail: function(res) {
                console.log("getQueryResumes fail", res);
            },
            complete: function(res) {
                wx.hideLoading();
                wx.stopPullDownRefresh();
            }
        });
    },
    getDefaultFilterData(pageI) {
        return {
            experienceId: "",
            educationId: "",
            experienceMin: '-1',
            experienceMax: '-1',
            currentUserInfoId: '',
            positionId: '',
            salaryMin: '0',
            salaryMax: '0',
            pageSize: this.data.pageSize,
            pageIndex: pageI,
            keyword: '',
            score: '',
            city:'',
            userStatus: ''
        };
    },
    getHomePositionData(){
        let that = this;
        wx.request({
            url: app.globalData.serverAddress.getHomePositionData,
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            success: function (res) {
                console.log("getHomePositionData response", res);
                if (res.statusCode == 200 && res.data.CodeStatus == 20000) {
                    let positionData = res.data.BodyContent;
                    that.setData({
                        positionFilter:positionData
                    })
                }
            },
            fail: function (res) {
                console.log("getHomePositionData fail", res);
            }
        });
    },
    getHomeFilterParams() {
        let that = this;
        wx.request({
            url: app.globalData.serverAddress.getHomeFilterParams,
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            success: function(res) {
                console.log("getHomeFilterParams response", res);
                if (res.statusCode == 200 && res.data.CodeStatus == 20000) {
                    let filterParams = res.data.BodyContent;
                    filterParams.ScoreData[0].active = true;
                    filterParams.WorkExpData[0].active = true;
                    filterParams.SalaryData[0].active = true;
                    filterParams.PositionData[0].active = true;
                    filterParams.StatusData[0].active = true;
                    filterParams.CityData[0].active = true;
                    that.setData({
                        filterParams: filterParams
                    })
                }
            },
            fail: function(res) {
                console.log("getHomeFilterParams fail", res);
            },
            complete: function(res) {

            }
        });
    },
    //点击评估条目
    clickItemEvaluate(e){
        let index = e.currentTarget.dataset.index;
        let name = this.data.resumeList[index].Name;
        wx.navigateTo({
            url: '/pages/new-pages/evaluate-pass/evaluate-pass?name=' + name
        })
    },
    checkStatus() {
        if (!app.globalData.isLogin) {
            Toast("请先登录");
            return false;
        }
        return true;
    },
    selectItem(e) {
        if (!this.checkStatus()) {
            return;
        }
        let index = e.currentTarget.dataset.index;
        let resumeId = this.data.resumeList[index].Id;
        wx.navigateTo({
            url: '/pages/new-pages/resume-detail/resume-detail?resumeId=' + resumeId
        });
    },
    //是否同城
    selectCityData(e){
        let index = e.currentTarget.dataset.index;
        let cityData = this.data.filterParams.CityData;
        for (let i = 0; i < cityData.length; i++) {
            cityData[i].active = false;
        }
        cityData[index].active = true;
        let key = `filterParams.CityData`
        this.setData({
            [key]: cityData
        })
    },
    //是否可立即工作
    selectWorkSatus(e) {
        let index = e.currentTarget.dataset.index;
        let workStatus = this.data.filterParams.StatusData;
        for (let i = 0; i < workStatus.length; i++) {
            workStatus[i].active = false;
        }
        workStatus[index].active = true;
        let key = `filterParams.StatusData`
        this.setData({
            [key]: workStatus
        })
    },
    //星级评价选择
    selectScore(e) {
        let index = e.currentTarget.dataset.index;
        let score = this.data.filterParams.ScoreData;
        for (let i = 0; i < score.length; i++) {
            score[i].active = false;
        }
        score[index].active = true;
        let key = `filterParams.ScoreData`
        this.setData({
            [key]: score
        })
    },
    //弹框学历选择
    selectEducation(e) {
        let index = e.currentTarget.dataset.index;
        let education = this.data.filterParams.EducationData;
        for (let i = 0; i < education.length; i++) {
            education[i].active = false;
        }
        education[index].active = true;
        let key = `filterParams.EducationData`;
        this.setData({
            [key]: education
        });
    },
    //弹框经验选择
    selectWorkExp(e) {
        let index = e.currentTarget.dataset.index;
        let workExp = this.data.filterParams.WorkExpData;
        for (let i = 0; i < workExp.length; i++) {
            workExp[i].active = false;
        }
        workExp[index].active = true;
        let key = `filterParams.WorkExpData`;
        this.setData({
            [key]: workExp
        });
    },
    //弹框薪资选择
    selectSalary(e) {
        let index = e.currentTarget.dataset.index;
        let salary = this.data.filterParams.SalaryData;
        for (let i = 0; i < salary.length; i++) {
            salary[i].active = false;
        }
        salary[index].active = true;
        let key = `filterParams.SalaryData`;
        this.setData({
            [key]: salary
        });
    },
    //点击弹框空白处
    clickFull() {
        let data = {
            popupObj: this.data.popupObj
        };
        data.popupObj.isShowPopup = false;
        data.popupObj.isAnim = false;
        this.setData(data);
    },
    //要求筛选事件
    clickFilter() {
        let that = this;
        //根据要求标签的相对位置改变弹出框的弹出位置
        const query = wx.createSelectorQuery()
        query.select('#filter').boundingClientRect(function(res) {
            that.setData({
                popupTop: (res.top + res.height) + "px"
            })
        })
        query.exec()
        let data = {
            popupObj: this.data.popupObj
        };
        data.popupObj.isShowPopup = !data.popupObj.isShowPopup;
        data.popupObj.isAnim = !data.popupObj.isAnim;
        this.setData(data);
    },
    //职能筛选
    clickFilterLabel() {
        let parmas = this.data.positionFilter;
        wx.navigateTo({
            url: '/pages/new-pages/filter-label/filter-label?'//数据量太大导致下一个页面刚进入会有几秒卡死parmas=' + JSON.stringify(parmas)
        })
    },
    //banner广告栏点击事件
    clickSwipers(e) {
        let index = e.currentTarget.dataset.index
        let url = ''
        switch(index){
            case 0:
                url = '/pages/new-pages/work-out/work-out'
                break;
            case 1:
                url = '/pages/new-pages/online-work/online-work'
                break;
            default:
                url = '/pages/new-pages/online-work/online-work'
                break;
        }
        wx.navigateTo({
            url: url
        });
    },
    //四个快捷导航
    clickAdv(e) {
        let index = e.currentTarget.dataset.index;
        let filterObj = this.getSelectFilterData();//先获取筛选条件
        let positionId = '';
        let userStatus = '';
        switch (index) {
            case '1':
                positionId = 'f001';
                break;
            case '2':
                positionId = 'f002';
                break;
            case '3':
                positionId = 'f003'
                break;
            case '4':
                userStatus = '1'
                break;
        }
        filterObj.positionId = positionId;
        filterObj.userStatus = userStatus;
        wx.navigateTo({
          url: '/pages/new-pages/talent-search/talent-search?flag=1&obj=' + JSON.stringify(filterObj)+'&index='+index
        })
    },
    //弹框重置条件
    clickReset() {
        let filterParams = this.data.filterParams;
        let workExp = filterParams.WorkExpData;
        for (let i = 1; i < workExp.length; i++) {
            workExp[i].active = false;
        }
        workExp[0].active = true;
        let salary = filterParams.SalaryData;
        for (let i = 1; i < salary.length; i++) {
            salary[i].active = false;
        }
        salary[0].active = true;
        let statusData = filterParams.StatusData;
        for (let i = 1; i < statusData.length; i++) {
            statusData[i].active = false;
        }
        statusData[0].active = true;
        let score = filterParams.ScoreData;
        for (let i = 1; i < score.length; i++) {
            score[i].active = false;
        }
        score[0].active = true;
        let city = filterParams.CityData;
        for (let i = 1; i < city.length; i++) {
            city[i].active = false;
        }
        city[0].active = true;
        this.setData({
            filterParams: filterParams
        })
    },
    //弹框确定条件
    clickConfirm() {
        let data = this.getSelectFilterData();
        this.getQueryResumes(data, false);
        let popupObj = this.data.popupObj;
        popupObj.isAnim = false;
        popupObj.isShowPopup = false;
        this.setData({
            popupObj: popupObj
        })
    },
    //通过index将点击的职能active设置为true
    setFromIndexActive(index) {
        let wayList = this.data.positionFilter;
        for (let i = 0; i < wayList.length; i++) {
            wayList[i].active = false;
        }
        wayList[index].active = true;
        this.setData({
            positionFilter: wayList
        });
        console.log(wayList)
    },
    getSelectFilterData() {
        let salarys = this.data.filterParams.SalaryData;
        let salaryObj = {};
        for (let i = 0; i < salarys.length; i++) {
            if (salarys[i].active) {
                salaryObj = salarys[i];
                break;
            }
        }
        let workExp = this.data.filterParams.WorkExpData;
        let worExpObj = {};
        for (let i = 0; i < workExp.length; i++) {
            if (workExp[i].active) {
                worExpObj = workExp[i];
                break;
            }
        }
        //获取已选择的职能id
        let wayList = this.data.filterParams.PositionData;
        let wayObj = {};
        for (let i = 0; i < wayList.length; i++) {
            if (wayList[i].active) {
                wayObj = wayList[i];
                break;
            }
        }
        //可立即工作筛选
        let statuList = this.data.filterParams.StatusData;
        let statuValue = '';
        for (let i = 0; i < wayList.length; i++) {
            if (statuList[i].active) {
                statuValue = statuList[i].value;
                break;
            }
        }
        //评分筛选
        let scoreList = this.data.filterParams.ScoreData;
        let scoreValue = '';
        for (let i = 0; i < scoreList.length; i++) {
            if (scoreList[i].active) {
                scoreValue = scoreList[i].value;
                break;
            }
        }
        //是否同城
        let cityList = this.data.filterParams.CityData;
        let cityValue = '';
        for (let i = 0; i < cityList.length; i++) {
            if (cityList[i].active) {
                if (cityList[i].text == '全部'){
                    cityValue = ''
                }else{
                    cityValue = this.data.currentCity;
                }
                break;
            }
        }
        let that = this;
        return{
            experienceId: worExpObj.id,
            educationId: "",
            experienceMin: worExpObj.min,
            experienceMax: worExpObj.max,
            currentUserInfoId: '',
            positionId: wayObj.Id,
            salaryMin: salaryObj.min,
            salaryMax: salaryObj.max,
            pageSize: that.data.pageSize,
            score: scoreValue,
            userStatus: statuValue,
            city: cityValue,
            pageIndex: 0
        };
    },
    //弹框拦截滑动事件
    interceptCatchMove() {},
    //搜索框点击事件
    clickSearch() {
        wx.navigateTo({
            url: '/pages/new-pages/talent-search/talent-search'
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        cerealsToast = this.selectComponent('#cereals-toast')
        let that = this;
        if (app.userInfo) {
            console.log(app.userInfo)
            this.doLogin(app.userInfo.Token, app.userInfo.Id);
            app.globalData.creditType = 4;
            app.saveCredit(function(count){
                cerealsToast.show(count);
            });
        } else {
            app.userInfoReadyCallback = res => {
                that.doLogin(app.userInfo.Token, app.userInfo.Id);
                app.globalData.creditType = 4;
                app.saveCredit(function (count) {
                    cerealsToast.show(count);
                });
            }
        }
        this.getBannersData();
        this.getQueryResumes('', false);
        this.getHomeFilterParams();
        this.getHomePositionData();
    },
    //登录云信IM
    doLogin: function(token, account) {
        console.log("yun xin，token:" + token + ",account:" + account);
        new IMController({
            token: token,
            account: account
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        app.locateReadyCallback = city => {
            console.log(city)
            //设置当前城市
            this.setData({
                currentCity: city
            })
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {
        this.clickFull();
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {
        let data = this.getSelectFilterData();
        data.pageIndex = 0;
        this.getQueryResumes(data, false);
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {
        let data = this.getSelectFilterData();
        this.getQueryResumes(data, true);
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {

    }
})